package pl.elka.pszt.view;

import java.awt.Component;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

/**
 * Pomocnicza klasa do wyboru pliku.
 * 
 * @author Andrzej Makarewicz
 * 
 */
public class FilePickingHelper {
	
	public static final String DEFAULT_EXTENSION = "txt";
	
	private static final FileFilter DEFAULT_FILE_FILTER = new KnowledgeFileFilter();
	
	private FilePickingHelper() {}
	
	/**
	 * Blokujace wybieranie pliku
	 * @param owner
	 * @return wybrany plik lub <code>null</code>
	 */
	public static File openFolderChooser(Component owner) {
		JFileChooser fileChooser = new JFileChooser(new File("."));
		fileChooser.setAcceptAllFileFilterUsed(false);
		fileChooser.setMultiSelectionEnabled(false);
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setFileFilter(DEFAULT_FILE_FILTER);
		
		switch (fileChooser.showOpenDialog(owner)) {
		case JFileChooser.APPROVE_OPTION:
			return fileChooser.getSelectedFile();
		default:
			return null;
		}
	}
	
	private static class KnowledgeFileFilter extends FileFilter {
		
		@Override
        public boolean accept(File f) {
            return f != null && (f.isDirectory() || DEFAULT_EXTENSION.equalsIgnoreCase(getExtension(f)));
        }
		
		@Override
		public String getDescription() {
			return "txt";
		}
	}
	
	public static String getExtension(File f) {
        String ext = null;
        if (f != null) {
            String s = f.getName();
            int i = s.lastIndexOf('.');
            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1);
            }
        }
        return ext;
    }
}
